//
//  XMPPManager.m
//  XMPPMessage
//
//  Created by 刘永杰 on 15/11/20.
//  Copyright © 2015年 刘永杰. All rights reserved.
//

#import "XMPPManager.h"

typedef enum NSInteger
{
    connectIsLogin,
    connectIsRegister
    
}ConnectMode;

@interface XMPPManager ()<XMPPStreamDelegate, XMPPRosterDelegate, UIAlertViewDelegate>

@property (copy, nonatomic) NSString *password;
@property (assign, nonatomic) ConnectMode myConnectMode;
@property (strong, nonatomic) XMPPJID *fromJID;

@end

@implementation XMPPManager

+ (XMPPManager *)defaultManager
{
    static dispatch_once_t onceToken;
    static XMPPManager *manager = nil;
    dispatch_once(&onceToken, ^{
        
        manager = [[XMPPManager alloc] init];
        
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //初始化自己的通道管理器类
        self.XMPPStream = [[XMPPStream alloc] init];
        //设置服务器主机名（在后台管理里面看）
        self.XMPPStream.hostName = @"127.0.0.1";
        //设置端口号  默认5222
        self.XMPPStream.hostPort = 5222;
        //设置代理，在主线程里
        [self.XMPPStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
        
        XMPPRosterCoreDataStorage *coreDataStorage = [XMPPRosterCoreDataStorage sharedInstance];
        //初始化用户管理
        self.XMPPRoster = [[XMPPRoster alloc] initWithRosterStorage:coreDataStorage dispatchQueue:dispatch_get_main_queue()];
        [self.XMPPRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
        //把用户类放进管理器类里面
        [self.XMPPRoster activate:self.XMPPStream];
        
        //初始化存储信息内容的类
        XMPPMessageArchivingCoreDataStorage *ArchcoreDataStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
        self.archiving = [[XMPPMessageArchiving alloc] initWithMessageArchivingStorage:ArchcoreDataStorage dispatchQueue:dispatch_get_main_queue()];
        [self.archiving activate:self.XMPPStream];
        
        self.content = ArchcoreDataStorage.mainThreadManagedObjectContext;
        
    }
    return self;
}

-(void)connectWithUserName:(NSString *)userName andPassWord:(NSString *)passWord{
    
    //在发生登录注册的操作的时候，需要让我的通道类的连接断掉，防止出现连接混乱的情况
    if ([self.XMPPStream isConnected]) {
        
        [self.XMPPStream disconnect];
    }
    
    self.password = passWord;
    
    //保存的一些用户的信息
    //可以知道给别人发消息，还是别人发来的消息
    XMPPJID *jid = [XMPPJID jidWithUser:userName domain:@"127.0.0.1" resource:@"iOS"];
    
    self.XMPPStream.myJID = jid;
    //让stream去建立连接
    [self.XMPPStream connectWithTimeout:1.0f error:nil];
    
}

- (void)loginWithUserName:(NSString *)userName andPassword:(NSString *)password
{
    self.myConnectMode = connectIsLogin;
    [self connectWithUserName:userName andPassWord:password];
}

- (void)registerWithUsetName:(NSString *)userName andPassword:(NSString *)password
{
    self.myConnectMode = connectIsRegister;
    [self connectWithUserName:userName andPassWord:password];
}
//连接成功
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    switch (self.myConnectMode) {
        case connectIsLogin: {
            
            [self.XMPPStream authenticateWithPassword:self.password error:nil];
            break;
        }
        case connectIsRegister: {
            
            [self.XMPPStream registerWithPassword:self.password error:nil];
            break;
        }
            
        default:
            break;
    }
    
}
//连接失败
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    
}
//将要连接
- (void)xmppStreamWillConnect:(XMPPStream *)sender
{
    
}
//这个方法可以收到好友请求
- (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
    
    self.fromJID = presence.from;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"添加好友请求" message:@"加我吧！" delegate:self cancelButtonTitle:@"不添加" otherButtonTitles:@"好的", nil];
    
    [alert show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            
            //拒绝好友
            [self.XMPPRoster rejectPresenceSubscriptionRequestFrom:self.fromJID];
            break;
        case 1:
            
            [self.XMPPRoster acceptPresenceSubscriptionRequestFrom:self.fromJID andAddToRoster:YES];
            break;
            
        default:
            break;
    }
}

@end
